'use strict';

const Controller = require('egg').Controller;

const sendToWormhole = require('stream-wormhole');
const QrCode = require('qrcode-reader');
const Jimp = require('jimp');

class ToolsController extends Controller {

  // 数据表
  async index() {
    const ctx = this.ctx;
    const method = ctx.request.method;
    if (method === 'POST') {
      const tables = ctx.request.body.tables || [];
      const body = { status: 0, message: '参数错误' };
      if (tables.length) {
        const out_str = await ctx.service.tools.getBak(tables);
        if (out_str) {
          body.status = 1;
          body.message = '备份成功';
        } else {
          body.message = '备份失败';
        }
      }
      ctx.body = body;
      ctx.status = 200;
    } else {
      const res = await ctx.service.tools.getTableStatus();
      const data_list = {
        lists: res.data,
        total: res.total,
        table_num: res.data.length,
      };
      await ctx.render(ctx.view_path(), data_list);
    }
  }

  // 备份文件列表
  async restore() {
    const ctx = this.ctx;
    const method = ctx.request.method;
    if (method === 'POST') {
      const act = ctx.request.body.act || '';
      const file_name = ctx.request.body.id || '';
      if (act && file_name && /^sql_(.+)\.sql$/.test(file_name)) {
        switch (act) {
          case 'rmv':
            {
              const res = ctx.service.tools.removeSql(file_name);
              const body = res ? { status: 1, message: '删除成功' } : { status: 0, message: '删除失败' };
              ctx.body = body;
              ctx.status = 200;
              break;
            }
          case 'down':
            {
              const res = ctx.service.tools.downloadSql(file_name);
              if (res) {
                ctx.set('content-type', 'application/octet-stream');
                ctx.attachment(file_name);
                ctx.body = res;
                ctx.status = 200;
              } else {
                ctx.body = '';
                ctx.status = 403;
              }
              break;
            }
          default: break;
        }
      }
    } else {
      const data = ctx.service.tools.getSqlList();
      await ctx.render(ctx.view_path(), data);
    }
  }

  // 表的优化和修复
  async operate() {
    const ctx = this.ctx;
    const table = ctx.request.body.table || '';
    const act = ctx.request.body.act || '';
    const list = { op: 1, re: 2 };
    let res = false;
    if (ctx.helper.check_name(table) && list[act]) {
      res = ctx.service.tools.tableOp(list[act], table);
    }
    ctx.body = res ? { message: '操作成功' } : { message: '操作失败' };
    ctx.status = 200;
  }

  async qrcode() {
    const ctx = this.ctx;
    const text = ctx.request.query.text || '';
    if (text) {
      const img = ctx.helper.create_qrcode(text);
      ctx.type = 'image/png';
      ctx.body = img;
      ctx.status = 200;
    } else {
      await ctx.render(ctx.view_path());
    }
  }

  // 二维码内容识别
  async qrcode_text() {
    const ctx = this.ctx;
    const method = ctx.request.method;
    if (method === 'POST') {
      const parts = ctx.multipart();
      let part = null;
      while ((part = await parts()) != null) {
        // 如果是数组的话是 filed
        const filename = part.filename;
        if (filename) {
          try {
            const buffer = part.read();
            const image = await Jimp.read(buffer);
            const qr = new QrCode();
            qr.decode(image.bitmap);
            ctx.body = { status: 1, data: { url: qr.result.result } };
            ctx.status = 200;
          } catch (err) {
            await sendToWormhole(part); // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
            console.log(err);
            ctx.body = { status: 0, message: '无法识别此二维码，请更换二维码图片' };
            ctx.status = 200;
          }
        }
      }
    } else {
      await ctx.render(ctx.view_path());
    }
  }

}

module.exports = ToolsController;
